package com.example.springbootpro.controller.mysql;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.springbootpro.annotation.ResponseWrapper;
import com.example.springbootpro.empty.SysUser;
import com.example.springbootpro.exception.BusinessException;
import com.example.springbootpro.result.Result;
import com.example.springbootpro.util.JWTUtils;
import com.example.springbootpro.util.UserContext;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.springbootpro.util.JWTUtils.md5Encrypt;
import static com.example.springbootpro.util.JWTUtils.validatePassword;

@RestController
@RequestMapping("/sys_users")
public class SysUserController {

    @Autowired
    @Qualifier("mysqlJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    private final RowMapper<SysUser> userRowMapper = new BeanPropertyRowMapper<>(SysUser.class);

    @SneakyThrows
    @PostMapping("insertSysUser")
    public Result<Integer> createUser(@RequestBody SysUser user) {

        if (user.getUsername() == null || user.getPassword() == null) {
            throw new BusinessException("400", "用户名和密码不能为空");
        }

        String sql = "INSERT INTO sys_user (username, password) VALUES (?, ?)";
        int affectedRows = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
        return Result.success(affectedRows);
    }

    @SneakyThrows
    @GetMapping("getSysUserById/{id}")
    public Result<SysUser> getUserById(@PathVariable Long id) {
        String sql = "SELECT id,username,password FROM sys_user WHERE id = ?";
        try {
            SysUser user = jdbcTemplate.queryForObject(sql, userRowMapper, id);
            return Result.success(user);
        } catch (EmptyResultDataAccessException e) {
            throw new BusinessException("404", "用户ID不存在: " + id);
        }
    }

     @ResponseWrapper
    @GetMapping("getAllSysUser")
    public Result<List<SysUser>> getAllUsers() throws BusinessException {

        String sql = "SELECT id,username,password FROM sys_user order by id desc";

        List<SysUser> users = jdbcTemplate.query(sql, userRowMapper);
       if (users.isEmpty()) {
            throw new BusinessException("404", "暂无用户数据");
        }
        return Result.success(users);
    }

    @SneakyThrows
    @PutMapping("/{id}")
    public Result<Integer> updateUser(@PathVariable Long id, @RequestBody SysUser user) {
        String sql = "UPDATE sys_user SET username = ?, password = ? WHERE id = ?";
        int affectedRows = jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), id);
        if (affectedRows == 0) {
            throw new BusinessException("404", "用户ID不存在: " + id);
        }
        return Result.success(affectedRows);
    }

    @SneakyThrows
    @DeleteMapping("deleteSysUserById/{id}")
    public Result<Integer> deleteUser(@PathVariable Long id) {
        String sql = "DELETE FROM sys_user WHERE id = ?";
        int affectedRows = jdbcTemplate.update(sql, id);
        if (affectedRows == 0) {
            throw new BusinessException("404", "用户ID不存在: " + id);
        }
        return Result.success(affectedRows);
    }

    @SneakyThrows
    @GetMapping("/by-username")
    public Result<SysUser> getByUsername(@RequestParam String username) {
        String sql = "SELECT id,username,password FROM sys_user WHERE username = ?";
        try {
            SysUser user = jdbcTemplate.queryForObject(sql, userRowMapper, username);
            return Result.success(user);
        } catch (EmptyResultDataAccessException e) {
            throw new BusinessException("404", "用户名不存在: " + username);
        }
    }


    @Autowired
    private RedisTemplate<String,Object> redisTemplate ;

    @PostMapping("/login")
     public Result<Map<String, Object>> login(@RequestBody Map<String, String> credentials) throws BusinessException {
        String username = credentials.get("username");
        String password = credentials.get("password");
        String sql = "SELECT id, username, password FROM sys_user WHERE username = ?";
        try {
            SysUser user = jdbcTemplate.queryForObject(sql, userRowMapper, username);
            System.out.println(user);
            System.out.println(validatePassword(password,user.getPassword()+"dgfdffg"));
            if (!validatePassword(password,user.getPassword())) {
                throw new BusinessException("401", "用户名或密码错误");
            }
             String token = JWTUtils.generateToken(username,password);

             redisTemplate.opsForValue().set(
                    "USER_TOKEN:" + username,
                    token,
                    JWTUtils.EXPIRATION_DAYS,
                    TimeUnit.DAYS
            );
              return Result.success(Map.of(
                    "token", token,
                    "username", username,
                    "expiresIn", JWTUtils.EXPIRATION_DAYS * 24 * 3600 // 秒数
            ));

        } catch (EmptyResultDataAccessException e) {
            throw new BusinessException("401", "用户名或密码错误");
        }
    }
    @PostMapping("/registry")
    public Result<String> registry(@RequestBody Map<String, String> credentials) {
        String username = credentials.get("username");
        String password = credentials.get("password");

        // 参数校验
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return Result.error("400", "用户名和密码不能为空");
        }

        // 检查用户名是否已存在
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM sys_user WHERE username = ?",
                Integer.class,
                username
        );

        if (count > 0) {
            return Result.error("400", "用户名已存在");
        }

        // 密码加密（示例使用MD5，实际项目建议使用BCrypt）
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());

        // 创建用户
        String sql = "INSERT INTO sys_user (username, password) VALUES (?, ?)";
        int affectedRows = jdbcTemplate.update(sql, username, encryptedPassword);

        if (affectedRows > 0) {
            return Result.success("注册成功");
        } else {
            return Result.error("500", "注册失败");
        }
    }

    @PostMapping("/logout")
    public Result<String> logout(@RequestHeader("Authorization") String token) {
        try {
            // 验证token
            DecodedJWT jwt = JWTUtils.verifyToken(token.replace("Bearer ", ""));
            String username = jwt.getClaim("username").asString();

            // 从Redis删除token
            redisTemplate.delete("USER_TOKEN:" + username);

            // 清除ThreadLocal中的用户信息
            UserContext.clear();

            return Result.success("退出成功");
        } catch (Exception e) {
            return Result.error("401", "无效的Token");
        }
    }


}